<template>
    <div style="display: flex;justify-content: space-between;">
        <a-form size="small" :model="pageData" layout="inline" style="margin-bottom: 10px;" ref="formRef">
            <a-form-item label="月份">
                <a-month-picker class="bacClass" v-model="pageData.planMonthBegin" style="width:200px" />至
                <a-month-picker class="bacClass" v-model="pageData.planMonthEnd" style="width:200px" />
            </a-form-item>
            <a-form-item label="检查名称">
                <a-select popup-container="html" class="bacClass" v-model="pageData.planNameList" allow-search allow-clear
                    @focus="getPlanname('')" @search="getPlanname" :filter-option="false" style="width:370px" multiple :max-tag-count="2">
                    <a-option v-for="(item, index) in pageData.nameList" :value="item.planName" :key="index">
                        {{ item.planName }}
                    </a-option>
                </a-select>
            </a-form-item>
        </a-form>
        <Toolbar :items="['查询', '导出']" @select="doRefresh" @export="exportExcel">
        </Toolbar>
    </div>
    <div class="cssTable">
        <a-spin :loading="pageData.pageLoading" tip="加载中" dot
            style="height:100%;width: 98.5%;z-index:999 ;margin-left: 13px;">
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                :style="{ height: pageData.rHeight - 150 + 'px' }" :suppressDragLeaveHidesColumns="true"
                rowSelection="multiple" @grid-ready="gridReady" :defaultColDef="defaultColDef" class='ag-theme-alpine'
                :rowData="pageData.tableList" :columnDefs="tableColumns" :localeText="localeText1" @FilterChanged="FilterChangeds"></AgGridVuesCopys>
        </a-spin>
    </div>
</template>

<script lang='ts' setup>
import { reactive, toRefs, ref, onMounted, Ref } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { slicing } from '@/utils/caseFrimAndSecRig'
import { FormInstance } from "@arco-design/web-vue/es/form";
import { assTable } from '@/utils/assemblyLevelTable'
import { ro } from 'element-plus/es/locale'
const localeText1: any = ref(localeText)
const pageData: any = reactive({
    pageLoading: false,
    rHeight: 0,
    tableList: [],
    nameList: [],
    planNameList:[],
    planMonthBegin: '',
    planMonthEnd: '',
})

const defaultColDef: any = {
    sortable: true,
    resizable: true,
    filter: true,
}

const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
}

const tableColumns: any = [
    {
        headerName: '检查项',
        children: [
            { headerName: '检查名称', field: 'planName', width: 150 },
            { headerName: '检查内容', field: 'inspectContent', width: 150 },
            { headerName: '要求次数', field: 'inspectNumber', width: 150 },
            {
                headerName: '目标合格率', field: 'qualifiedRate', width: 150,
                cellRenderer: {
                    template: `<span v-if="val.planName != '合计'">{{ val.qualifiedRate + '%' }}</span>
                               <span v-if="val.planName == '合计'"></span>`,
                    setup(props: any) {
                        let val = ref(props.params.data)
                        return {
                            val,
                        }
                    },
                },
            }
        ],
    },
    {
        headerName: '织造一厂',
        children: [
            { headerName: '合格', field: 'qualifiedCount1', width: 100 },
            { headerName: '不合格', field: 'unqualifiedCount1', width: 100 },
            {
                headerName: '合格率', field: 'qualifiedRate1', width: 100,
                cellRenderer: (params: any) => {
                    let val = (params.value * 100).toFixed(1)
                    if (val > params.data.qualifiedRate || params.value.planName == '合计') {
                        return "<span>" + val + "%" + "</span>";
                    } else {
                        return "<span style='color:red;font-weight: bold;'>" + val + "%" + "</span>";
                    }
                },
            },
        ],
    },
    {
        headerName: '织造二厂',
        children: [
            { headerName: '合格', field: 'qualifiedCount2', width: 100 },
            { headerName: '不合格', field: 'unqualifiedCount2', width: 100 },
            {
                headerName: '合格率', field: 'qualifiedRate2', width: 100,
                cellRenderer: (params: any) => {
                    let val = (params.value * 100).toFixed(1)
                    if (val > params.data.qualifiedRate || params.value.planName == '合计') {
                        return "<span>" + val + "%" + "</span>";
                    } else {
                        return "<span style='color:red;font-weight: bold;'>" + val + "%" + "</span>";
                    }
                },
            },
        ],
    },
    {
        headerName: '织造三厂',
        children: [
            { headerName: '合格', field: 'qualifiedCount3', width: 100 },
            { headerName: '不合格', field: 'unqualifiedCount3', width: 100 },
            {
                headerName: '合格率', field: 'qualifiedRate3', width: 100,
                cellRenderer: (params: any) => {
                    let val = (params.value * 100).toFixed(1)
                    if (val > params.data.qualifiedRate || params.value.planName == '合计') {
                        return "<span>" + val + "%" + "</span>";
                    } else {
                        return "<span style='color:red;font-weight: bold;'>" + val + "%" + "</span>";
                    }
                },
            },
        ],
    },
    {
        headerName: '织造四厂',
        children: [
            { headerName: '合格', field: 'qualifiedCount4', width: 100 },
            { headerName: '不合格', field: 'unqualifiedCount4', width: 100 },
            {
                headerName: '合格率', field: 'qualifiedRate4', width: 100,
                cellRenderer: (params: any) => {
                    let val = (params.value * 100).toFixed(1)
                    if (val > params.data.qualifiedRate || params.value.planName == '合计') {
                        return "<span>" + val + "%" + "</span>";
                    } else {
                        return "<span style='color:red;font-weight: bold;'>" + val + "%" + "</span>";
                    }
                },
            },
        ],
    },
    {
        headerName: '织造中心',
         children: [
            { headerName: '合格', field: 'totalQualifiedCount', width: 100 },
            { headerName: '不合格', field: 'totalUnqualifiedCount', width: 100 },
            {
                headerName: '合格率', field: 'totalQualifiedRate', width: 100,
                cellRenderer: (params: any) => {
                    let val = (params.value * 100).toFixed(1)
                    if (val > params.data.qualifiedRate || params.value.planName == '合计') {
                        return "<span>" + val + "%" + "</span>";
                    } else { 
                        return "<span style='color:red;font-weight: bold;'>" + val + "%" + "</span>";
                    }
                },
            },
        ],
    },
]

//查询
const formRef = ref<FormInstance>();
function doRefresh() {
    formRef.value?.validate().then((err: any) => {
        if (!err) {
            pageData.pageLoading = true
            post({
                url: "/qms/inspectionPlanResult/buildInspectionQualityReport",
                data: {
                    planNameList: pageData.planNameList,
                    planMonthBegin: pageData.planMonthBegin,
                    planMonthEnd: pageData.planMonthEnd,
                    planType: 1,
                }
            })
                .then((res: any) => {
                    if (res.code === 200) {
                        pageData.tableList = res.data
                        gridOption.value.setRowData(res.data)
                        counts(pageData.tableList)
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }
    })
}

//检查名称
const getPlanname = (val: any) => {
    post({
        url: '/qms/inspectionPlan/listInspectionPlans',
        data: {
            planName: val ? val : '',
            planMonthBegin:pageData.planMonthBegin,
            planMonthEnd:pageData.planMonthEnd
        },
    }).then((res) => {
        if (res.code == 200) {
            //名称 去重
            var result = [];
            var obj = {};
            for (var i = 0; i < res.data.length; i++) {
                if (!obj[res.data[i].planName]) {
                    result.push(res.data[i]);
                    obj[res.data[i].planName] = true;
                }
            }
            pageData.nameList = result
        } else {
            Message.error({
                content: res.message,
                duration: 5000,
            })
        }
    })
}

// 底部合计
const calculateRate = (q: any, unq: any) => {
    const result: any = q / (q + unq);
    return isNaN(result) ? 0 : parseFloat(result);
}
function counts(data:any) {
    var sum1 = 0;
    var q1 = 0;
    var q2 = 0;
    var q3 = 0;
    var q4 = 0;
    var q5 = 0;
    var unq1 = 0;
    var unq2 = 0;
    var unq3 = 0;
    var unq4 = 0;
    var unq5 = 0;
    var rate1 = 0
    var rate2 = 0
    var rate3 = 0
    var rate4 = 0
    var rate5 = 0
    for (var i = 0; i < data.length; i++) {
        sum1 = sum1 + data[i].inspectNumber;
        q1 = q1 + data[i].qualifiedCount1;
        q2 = q2 + data[i].qualifiedCount2;
        q3 = q3 + data[i].qualifiedCount3;
        q4 = q4 + data[i].qualifiedCount4;
        q5 = q5 + data[i].totalQualifiedCount;
        unq1 = unq1 + data[i].unqualifiedCount1;
        unq2 = unq2 + data[i].unqualifiedCount2;
        unq3 = unq3 + data[i].unqualifiedCount3;
        unq4 = unq4 + data[i].unqualifiedCount4;
        unq5 = unq5 + data[i].totalUnqualifiedCount;
        rate1 = calculateRate(q1, unq1);
        rate2 = calculateRate(q2, unq2);
        rate3 = calculateRate(q3, unq3);
        rate4 = calculateRate(q4, unq4);
        rate5 = calculateRate(q5, unq5);
    }
    var nowRows = [
        {
            planName: '合计', inspectNumber: sum1,
            qualifiedCount1: q1, qualifiedCount2: q2, qualifiedCount3: q3, qualifiedCount4: q4, totalQualifiedCount: q5,
            unqualifiedCount1: unq1, unqualifiedCount2: unq2, unqualifiedCount3: unq3, unqualifiedCount4: unq4, totalUnqualifiedCount: unq5,
            qualifiedRate1: rate1, qualifiedRate2: rate2, qualifiedRate3: rate3, qualifiedRate4: rate4, totalQualifiedRate: rate5
        }
    ];
    gridOption.value.setPinnedBottomRowData(nowRows);
}

// 导出
const exportExcel = async () => {
    // 确保数据加载完成
    await doRefresh();

    let nowRow = pageData.tableList.map((row: any) => {
        Object.keys(row).forEach(key => {
            if (row[key] === null || row[key] === undefined || row[key] === 0) {
                row[key] = '0';
            }
        });
        row['totalQualifiedRate'] = parseFloat((Number(row['totalQualifiedRate']) * 100).toFixed(1)) + '%';
        row['qualifiedRate4'] = parseFloat((Number(row['qualifiedRate4']) * 100).toFixed(1)) + '%';
        row['qualifiedRate3'] = parseFloat((Number(row['qualifiedRate3']) * 100).toFixed(1)) + '%';
        row['qualifiedRate2'] = parseFloat((Number(row['qualifiedRate2']) * 100).toFixed(1)) + '%';
        row['qualifiedRate1'] = parseFloat((Number(row['qualifiedRate1']) * 100).toFixed(1)) + '%';
        row['qualifiedRate'] = row['qualifiedRate'] + '%';
        return row;
    });

    // 确保导出的时机与表格渲染时机一致
    await assTable(tableColumns, nowRow, '检查项按厂区统计报表');
}

const FilterChangeds = (params:any)=>{
    let data: any = {
    list: [],
  }
  params.api.forEachNodeAfterFilter((row: any) => {
    data.list.push(row.data)
  })
counts(data.list)
}

onMounted(() => {
    pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
    //弹出层的高
    if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight;
    }
    doRefresh()
})
</script>
<style lang='less' scoped>
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

:deep(.arco-select-view-multiple.arco-select-view-disabled .arco-select-view-tag) {
    color: #4e5969 !important;
    ;
    background-color: white;
    border-color: white;
    font-size: 14px
}
</style>